package com.cictec.middleware.gps.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.core.entity.BusLine;
import com.cictec.middleware.core.entity.DeparterSchedule;
import com.cictec.middleware.core.entity.DevDownTask;
import com.cictec.middleware.feign.distribute.SendPlatformMessageToTerminalService;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.BusInstanceEngine;

/**
 * 切换线路
 * 
 * @author ql
 *
 */
@Service
public class BusChangeLineService {

	private static Logger logger = LoggerFactory.getLogger(BusChangeLineService.class);
	
	@Autowired
	private BusInstanceEngine busInstanceEngine;
	@Autowired
	private ScheduleService scheduleService;
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private SendPlatformMessageToTerminalService sendPlatformMessageToTerminalService;

	private Map<String, BusChangeLineMark> changeMark = new HashMap<String, BusChangeLineMark>();
	
	/**
	 * 定时切换线路校验
	 */
	public void changeLineCheck() {

//		// 提前2分钟发送语音提示
//		BusInstance busInstance1 = busInstanceEngine.getBusInstanceByDevCode("5290");
//		if(PMSUtils.isEmpty(busInstance1.getLineUuid())){
//			return;
//		}
//		
//		DeparterSchedule ds1 = new DeparterSchedule();
//		ds1.setDepartureTime(DateUtils.getDateFromSeconds(new Date(), 60));
//		ds1.setBrsdBusUuid("0334ee4921994df983bc");
//		ds1.setBrsdRemarkType("2");
//		ds1.setBrsdBranchLineUuid("0e6fbed50e66457ebd04");
//		
//		
//		if(ds1 != null 
//				&& ds1.getDepartureTime() != null
//				&& ds1.getDepartureTime().getTime() >= busInstance1.getCurrentTime().getTime()
//				&& !PMSUtils.isEmpty(ds1.getBrsdBranchLineUuid())
//				&& !PMSUtils.isEmpty(ds1.getBrsdRemarkType())
//				&& !ds1.getBrsdRemarkType().equals("1")
//				){
//			
//			
//			
//			// 提前2分钟发送语音提示
//			sendVoice(busInstance1, ds1);
//
//			// 切换线路、语音
////			sendVoiceAndChangeLine(busInstance1, ds1);
//			
//		}
//		if(true){
//			
//			return;
//		}
//		scheduleService.reloadLineSchedule("422df3625d8b46ef876c");
//		scheduleService.reloadLineSchedule("82c045efb5754705a30b");
		
		List<BusInstance> busList = busInstanceEngine.getAllBusInstance(true);

		Date currentTime = new Date();
		for (BusInstance busInstance : busList) {

			if(PMSUtils.isEmpty(busInstance.getLineUuid())){
				continue;
			}
			
//			System.out.println(DateUtils.formatDateTime(currentTime));
//			DeparterSchedule ds = scheduleService.getDeparterScheduleNearest(busInstance.getLineUuid(), null, busInstance.getBusUuid(), busInstance.getCurrentTime(), 0, false);
			DeparterSchedule ds = scheduleService.getDeparterScheduleNearestInAllLine(busInstance.getBusUuid(), busInstance.getTime(), 0, true);
//			System.out.println(busInstance.getLineName() + "\t" + ds.getLineName() + "\t"+DateUtils.formatDateTimeMinute(ds.getDepartureTime()) + "\t" + ds.getBrsdRemarkType());
//			System.out.println(DateUtils.formatDateTime(busInstance.getCurrentTime()) + "\t" + DateUtils.formatDateTime(ds.getDepartureTime()));
			if(ds != null 
					&& ds.getDepartureTime() != null
//					&& ds.getDepartureTime().getTime() >= busInstance.getCurrentTime().getTime()	// 此判定可能因为位置坐标上传错误导致时间错误，无法切换
					&& ds.getDepartureTime().getTime() >= currentTime.getTime()
//					&& !PMSUtils.isEmpty(ds.getBrsdBranchLineUuid())
//					&& !PMSUtils.isEmpty(ds.getBrsdRemarkType())
//					&& !ds.getBrsdRemarkType().equals("1")
					){
				logger.debug("【切换线路】最近的发车时刻：{} {}", ds.getLineName(), DateUtils.formatDateTimeMinute(ds.getDepartureTime()));
				
				// 提前2分钟发送语音提示
				sendVoice(busInstance, ds);

				// 切换线路、语音
				sendVoiceAndChangeLine(busInstance, ds);
				
			}
		}
	}
	
	/**
	 * 发送语音提示
	 */
	public void sendVoice(BusInstance busInstance, DeparterSchedule ds){
		
		// 内容：线路切换通知 下一趟发线路15路,上行,发车时刻 12:15 
		Date sysTime = new Date();
//		Date pointTime = busInstance.getCurrentTime();
		String busUuid = busInstance.getBusUuid();
		BusLine busLine = null;
		if(!PMSUtils.isEmpty(ds.getBrsdBranchLineUuid())){
			busLine = busLineService.getLineByLineUuid(ds.getBrsdBranchLineUuid());
		}else{
			busLine = busLineService.getLineByLineUuid(ds.getLineUuid());
		}
		
//		System.out.println("当前线路：" + busInstance.getLineName());
//		System.out.println("【语音匹配到】："+busLine.getLineName() + "\t" + ds.getBrsdDepartureTime() + "\t" + DateUtils.formatDateTimes(busInstance.getCurrentTime()));
		if(busLine == null || busLine.getLineUuid().equals(busInstance.getLineUuid())){
			return;
		}
		
		String msg = "";
		BusChangeLineMark mark = null;
		
		
		
		// 如果时间差 2分钟以内
		if(changeMark.containsKey(busUuid)){
			mark = changeMark.get(busUuid);
			
//			if(!mark.lineUuid.equals(ds.getLineUuid()) && !mark.isSendVoice ){
			if(!mark.lineUuid.equals(busLine.getLineUuid())){
				if(DateUtils.secondInterval(sysTime, ds.getDepartureTime()) <= 2*60 && !mark.isSendVoice){
					// 发送切换线路语音提示
					mark.lineUuid = busLine.getLineUuid();
					mark.isSendVoice = true;
					
					msg = formatVoiceMessage(busLine, ds);
					
				}
			}else{
				mark.isSendVoice = false;
				mark.isSendVoiceAndChange = false;
			}
		}else{
			if(DateUtils.secondInterval(sysTime, ds.getDepartureTime()) <= 2*60){
				// 发送切换线路语音提示
				mark = new BusChangeLineMark(busUuid, busLine.getLineUuid());
				mark.isSendVoice = true;
				changeMark.put(busUuid, mark);
				
				msg = formatVoiceMessage(busLine, ds);
				
			}
			
		}
		
		/*发送切换线路语音 */
		sendChangeLineVoice(busInstance, ds, busLine, msg);
	}
	
	private String formatVoiceMessage(BusLine busLine, DeparterSchedule ds){
		String lineName = busLine.getLineName();
//		String lineName = "";
//		char[] lineNamArr = busLine.getLineName().toCharArray();
//		for (int i = 0; i < lineNamArr.length; i++) {
//			lineName += lineName.length() == 0 ? lineNamArr[i] : "," + lineNamArr[i];
//		}
		lineName = lineName.endsWith("路")?lineName:lineName+"路";
		
		String msg = "";
		msg += "线路切换通知";
		msg += "，下一趟发车线路" + lineName;
//		msg += ds.getBrsdType().equals("1")? "上行":"下行";
		msg += "，2分钟后将自动切换线路";
		msg += "，发车时刻" + DateUtils.formatDate(ds.getDepartureTime(), "HH:mm");
		
		return msg;
	}
	
	/**
	 * 发送语音提示并切换线路
	 */
	public void sendVoiceAndChangeLine(BusInstance busInstance, DeparterSchedule ds){
		
		// 内容：线路切换通知 下一趟发线路15路,上行,发车时刻 12:15 
		
		Date sysTime = new Date();
//		Date pointTime = busInstance.getCurrentTime();
		String busUuid = busInstance.getBusUuid();
		String pointLineUuid = busInstance.getLineUuid();
		BusLine busLine = null;
		if(!PMSUtils.isEmpty(ds.getBrsdBranchLineUuid())){
			busLine = busLineService.getLineByLineUuid(ds.getBrsdBranchLineUuid());
		}else{
			busLine = busLineService.getLineByLineUuid(ds.getLineUuid());
		}
		if(busLine == null || busLine.getLineUuid().equals(busInstance.getLineUuid())){
			return;
		}
//		System.out.println("【指令匹配到】："+busLine.getLineName() + "\t" + ds.getBrsdDepartureTime() + "\t" + DateUtils.formatDateTimes(busInstance.getCurrentTime()));
		
		boolean isSend = false;
		BusChangeLineMark mark = null;
		
		
		// 10秒的误差
		if(changeMark.containsKey(busUuid)){
			mark = changeMark.get(busUuid);
			
			if(!mark.lineUuid.equals(pointLineUuid)){
				if(DateUtils.secondInterval(sysTime, ds.getDepartureTime()) <= 30 && !mark.isSendVoiceAndChange){
					isSend = true;
					
					// 发送切换线路语音提示
					mark.lineUuid = busLine.getLineUuid();
					mark.isSendVoiceAndChange = true;
				}
			}else{
				mark.isSendVoiceAndChange = false;
			}
		}else{
			if(DateUtils.secondInterval(sysTime, ds.getDepartureTime()) < 30){
				isSend = true;
				
				// 发送切换线路语音提示
				mark = new BusChangeLineMark(busUuid, busLine.getLineUuid());
				mark.isSendVoiceAndChange = true;
				changeMark.put(busUuid, mark);
			}
		}
		
		if(isSend){
			List<Integer> lineIds = busLine.getBusLineIds();
			Integer lineId = null;
			if(lineIds.size() > 0){
				lineId = lineIds.get(0);
			}
			if(lineId == null){
				return;
			}
			sendPlatformMessageToTerminalService.sendChangeLineMessage(busInstance.getDevCode(), String.valueOf(lineId), null);
			logger.debug("【切换线路】【下发切换线路指令】匹配线路时刻 {} lineName:{} departureTime:{}", busInstance.getBusNumber(), busLine.getLineName(), ds.getBrsdDepartureTime());
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			/*发送切换线路语音 */
			String lineName = busLine.getLineName();
			lineName = lineName.endsWith("路") ? lineName : lineName + "路";
			String msg = "车辆线路切换，当前线路" + lineName;
			sendChangeLineVoice(busInstance, ds, busLine, msg);
		}
	}
	
	
	private void sendChangeLineVoice(BusInstance busInstance, DeparterSchedule ds, BusLine busLine, String msg){
		if(!PMSUtils.isEmpty(msg)){
			DevDownTask downTask = new DevDownTask();
			downTask.setTaskUuid(PMSUtils.getUUID());
			downTask.setName("消息广播");
			downTask.setType(Constants.VAL_TASK_TYPE_7);
			downTask.setContent(msg);
//			downTask.setCreator(creatorUuid);
			downTask.setCreateTime(DateUtils.getDateTimes());
			downTask.setStatus(Constants.VAL_TASK_STATUS_0);

			downTask.setTdUuid(PMSUtils.getUUID());
			downTask.setDevUuid(busInstance.getDevUuid());
			downTask.setBusUuid(busInstance.getBusUuid());
			downTask.setSendStatus(Constants.VAL_TASK_SEND_STATUS_1);
			downTask.setSendTime(DateUtils.getDateTimes());
			
			
			logger.debug("【切换线路】【下发切换线路语音】匹配线路时刻 {} lineName:{} departureTime:{} content:{}", busInstance.getBusNumber(), busLine.getLineName(), ds.getBrsdDepartureTime(), msg);

		}
	}
	
	class BusChangeLineMark {
		String busUuid;
		String lineUuid;
		
		boolean isSendVoice = false;
		boolean isSendVoiceAndChange = false;

		public BusChangeLineMark(String busUuid, String lineUuid) {
			this.busUuid = busUuid;
			this.lineUuid = lineUuid;
		}
	}
}

